package cn.antcore.common.security.handler;

import cn.antcore.common.exception.ReturnT;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletResponse;
import lombok.Getter;
import org.springframework.http.HttpStatus;

import java.io.IOException;

/**
 * 认证处理类
 * <br>
 * Created by Hong 2024/5/21
**/
@Getter
public abstract class AbstractAuthenticationHandler {

    private final ObjectMapper objectMapper;

    protected AbstractAuthenticationHandler(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    protected void failure(HttpServletResponse response, ReturnT returnT) throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        response.setStatus(HttpStatus.OK.value());
        response.getWriter().write(objectMapper.writeValueAsString(returnT));
        response.getWriter().flush();
    }

    protected void success(HttpServletResponse response, Object body) throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        response.setStatus(HttpStatus.OK.value());
        response.getWriter().write(objectMapper.writeValueAsString(ReturnT.success(body)));
        response.getWriter().flush();
    }
}
